package cn.gson.zuche.model.dao;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import cn.gson.zuche.model.GlobalParamHandler;
import cn.gson.zuche.model.bean.Lxr;
import cn.gson.zuche.model.bean.User;
import cn.gson.zuche.model.jdbc.MySqlDb;
import cn.gson.zuche.model.jdbc.ParamHandler;
import cn.gson.zuche.model.jdbc.ResultHandler;

public class Lxrdao implements ResultHandler<Lxr> {
	private MySqlDb db = MySqlDb.getInstance();

	/**
	 * 根据用户id 来查询改用户 绑定的联系人
	 * 
	 * @param userid
	 * @return
	 * @throws SQLException
	 */
	public List<Lxr> finallbyuserid(String userid) throws SQLException {
		String sql = "select * from lxr where lxr_user_id = '" + userid + "'";
		return db.executeQuery(sql, this);
	}

	/**
	 * 联系人的插入
	 * 
	 * @param lxr
	 * @return
	 * @throws SQLException
	 */
	public boolean insertLxr(Lxr lxr) throws SQLException {
		String sql = "INSERT INTO lxr(lxr_name,lxr_phone,lxr_sfz,lxr_email,lxr_user_id) VALUES  (?,?,?,?,?)";
		return db.executeUpdate(sql, new save(lxr)) > 0;
	}

	public boolean deleteLxr(String lxrid) throws SQLException {
		String sql = "delete from lxr WHERE lxr_id=?";
		return db.executeUpdate(sql, new GlobalParamHandler(lxrid)) > 0;
	}
	/**
	 * 查找是否存在此联系人
	 */
	public List<Lxr> finallbylxrsfz(String lxrsfz) throws SQLException{
		String sql = "select * from lxr where lxr_sfz = '"+lxrsfz+"'";
		return db.executeQuery(sql, this);
	}
	
	/**
	 * 插入新联系人
	 */
	public boolean insertxinyonhu(final Lxr lxr) throws SQLException{
		String sql = "INSERT into lxr(lxr_name,lxr_phone,lxr_sfz,lxr_email,lxr_user_id) VALUES(?,?,?,?,?)";
		return db.executeUpdate(sql,new save(lxr))>0;
}

	@Override
	public Lxr doHander(Map<String, Object> row) {
		Lxr lxr = new Lxr();
		lxr.setLxrid(Integer.parseInt(row.get("lxr_id") + ""));
		lxr.setLxremail(row.get("lxr_email") + "");
		lxr.setLxrname(row.get("lxr_name") + "");
		lxr.setLxrsfz(row.get("lxr_sfz") + "");
		lxr.setLxrphone(row.get("lxr_phone") + "");
		lxr.setLxruserid(Integer.parseInt(row.get("lxr_user_id") + ""));
		return lxr;
	}

	private class save implements ParamHandler {
		Lxr lxr = new Lxr();

		save(Lxr lxr) {
			this.lxr = lxr;
		}

		public void doHander(PreparedStatement pStatement) throws SQLException {
			pStatement.setString(1, lxr.getLxrname() );
			pStatement.setString(2, lxr.getLxrphone());
			pStatement.setString(3, lxr.getLxrsfz());	
			pStatement.setString(4, lxr.getLxremail());
			pStatement.setInt(5,lxr.getLxruserid());	
		}

	}
}
